package com.neuedu.nep.javaIO;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonIO {

    public static void writer(String filepath,Object object){
        ObjectMapper objectMapper = new ObjectMapper();

        try{
            objectMapper.writeValue(new File(filepath), object);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static <T>Object read(String filepath,T t){
        Object obj=null;
        List list=new ArrayList<>();
        try{
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(new File(filepath));
            Iterator<JsonNode> iterator=jsonNode.iterator();
            while(iterator.hasNext()){
                JsonNode node=iterator.next();
                T temp=(T) objectMapper.treeToValue(node,t.getClass());
                list.add(temp);
            }
            obj=list;
        }catch(Exception e){
            e.printStackTrace();
        }
        return obj;
    }

    public static<T> List<T> readList(String filepath,T t){
        Object obj=null;
        obj=read(filepath,t);
        return (List<T>) obj;
    }
}
